package com.platform.article.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.article.client.UserClient;
import com.platform.article.enums.AuditStatusEnum;
import com.platform.article.model.ArticleDO;
import com.platform.article.vo.ArticleAuditInfoVO;
import com.platform.article.service.ArticleService;
import com.platform.common.annotation.ApiResponseBody;
import com.platform.common.entity.PageResult;
import com.platform.common.result.ApiException;
import com.platform.common.result.ApiExceptionEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author shuc
 */
@ApiResponseBody
@Controller
@RequestMapping("/article")
public class AuditController {
    @Resource
    private ArticleService articleService;

    @Resource
    private UserClient userClient;

    @PostMapping("/audit")
    public Boolean audit(@RequestBody Map<String, String> params) {
        ArticleDO articleDO = ArticleDO.builder()
                .id(params.get("id"))
                .status(1)
                .build();
        Boolean result = articleService.updateById(articleDO);
        if (!result) {
            throw new ApiException(ApiExceptionEnum.DB_FAIL);
        }
        return true;
    }

    @GetMapping("/audit/page")
    public PageResult<ArticleAuditInfoVO> pageUnauditedArticles(@RequestParam Integer page,
                                                                @RequestParam Integer size) {
        Page<ArticleDO> articleDOPage = articleService.pageByStatus(AuditStatusEnum.UNAUDITED.getType(), new Page<>(page, size));
        return PageResult.<ArticleAuditInfoVO>builder()
                .total(articleDOPage.getTotal())
                .rows(articleDOPage.convert(articleDO -> {
                    ArticleAuditInfoVO articleAuditInfoVO = new ArticleAuditInfoVO();
                    BeanUtils.copyProperties(articleDO, articleAuditInfoVO, "author");
                    articleAuditInfoVO.setAuthor(userClient.idToAccount(articleDO.getAuthorId()));
                    return articleAuditInfoVO;
                }).getRecords())
                .build();
    }
}
